import data from "../../../../core/cache_data";
import { ReplacePageAni } from "../../../../core/game";
import Utils, { Sync } from "../../../../core/utils";
import CheckBox from "../../../../prefabs/check_box";
import { PingPongGameConfig } from "../page_game/page_game";
import PlayerArea from "../page_game/player_area";

const { ccclass, property } = cc._decorator;

@ccclass
export default class PageSetup extends cc.Component {
    @property(cc.EditBox)
    ebHealth: cc.EditBox = null;
    @property(cc.EditBox)
    ebSize: cc.EditBox = null;
    @property(cc.EditBox)
    ebDoorSize: cc.EditBox = null;
    @property(cc.EditBox)
    ebBallSpeed: cc.EditBox = null;
    @property(CheckBox)
    cbBallSpeedLimitation: CheckBox = null;


    @property(PlayerArea)
    area: PlayerArea = null;

    async onClickStart() {
        this.updateConfig();

        this.node.destroy();
        await Sync.NextUpdate();
        Utils.game.resReplacePage({
            name: "page_game",
            ani: ReplacePageAni.Fade
        });
    }

    protected onLoad(): void {
        this.updateConfig();
        this.refresh();
        this.schedule(this.update01, 0.1);
    }

    refresh() {
        let config = data.cache.get<PingPongGameConfig>("ping-pong-game-config");

        this.ebHealth.string = `${config.healthMax}`;
        this.ebSize.string = `${config.handleSize}`;
        this.ebDoorSize.string = `${config.doorSize}`;
        this.ebBallSpeed.string = `${config.limitSpeed}`;
        this.cbBallSpeedLimitation.checked = config.speedLimitation;

        this.area.setDoorSize(config.doorSize);

        this.area.handle.node.width = config.handleSize;
        this.area.handle.node.height = config.handleSize;
        this.area.lbScore.string = `${config.healthMax}`;
        let col = this.area.handle.getComponent(cc.PhysicsCircleCollider);
        col.radius = config.handleSize / 2;
        col.apply();
    }
    update01(dt: number): void {
        this.updateConfig();
        this.refresh();
    }
    updateConfig() {
        let rec = data.cache.rec("ping-pong-game-config", new PingPongGameConfig());
        rec.data.doorSize = Number(this.ebDoorSize.string);
        rec.data.healthMax = Number(this.ebHealth.string);
        rec.data.speedLimitation = this.cbBallSpeedLimitation.checked;
        rec.data.limitSpeed = Number(this.ebBallSpeed.string);
        rec.data.handleSize = Number(this.ebSize.string);
    }
};